package io.renren.modules.contract.service.impl;

import io.renren.common.utils.BigDecimalUtils;
import io.renren.modules.contract.dao.ContractPaymentDao;
import io.renren.modules.contract.entity.*;
import io.renren.modules.contract.service.CorporateCheckingService;
import io.renren.modules.project.dao.ProjectApplicantInfoDao;
import io.renren.modules.project.dao.ProjectEntityDao;
import io.renren.modules.project.entity.ProjectApplicantInfoEntity;
import io.renren.modules.project.entity.ProjectEntityEntity;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.renren.modules.contract.dao.ContractReceiptDao;
import io.renren.modules.contract.service.ContractReceiptService;



@Service("contractReceiptService")
public class ContractReceiptServiceImpl implements ContractReceiptService {
	@Autowired
	private ContractReceiptDao contractReceiptDao;
	@Autowired
    private ContractPaymentDao contractPaymentDao;
	@Autowired
	private ProjectEntityDao projectEntityDao;
	@Autowired
	private ProjectApplicantInfoDao projectApplicantInfoDao;
	@Autowired
	private CorporateCheckingService corporateCheckingService;
	
	@Override
	public ContractReceiptEntity queryObject(String id){
		return contractReceiptDao.queryObject(id);
	}
	
	@Override
	public List<ContractReceiptEntity> queryList(Map<String, Object> map){
		return contractReceiptDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return contractReceiptDao.queryTotal(map);
	}
	
	@Override
	public void save(ContractReceiptEntity contractReceipt){
		contractReceiptDao.save(contractReceipt);
	}
	
	@Override
	public void update(ContractReceiptEntity contractReceipt){

		if (StringUtils.isNotBlank(contractReceipt.getReportingUnit())){
			String unitId = contractReceipt.getReportingUnit();
           //判断输入的项目申请方是否存在
			ProjectApplicantInfoEntity unitCount = projectApplicantInfoDao.queryObject(contractReceipt.getReportingUnit());
			//如果不存在则进行新增操作
			if (unitCount == null){
				unitId = UUID.randomUUID().toString().replaceAll("-","");
				ProjectApplicantInfoEntity projectApplicantInfoEntity = new ProjectApplicantInfoEntity();
				projectApplicantInfoEntity.setId(unitId);
				projectApplicantInfoEntity.setApplicantName(contractReceipt.getReportingUnit());
				projectApplicantInfoDao.save(projectApplicantInfoEntity);
				contractReceipt.setReportingUnitName(contractReceipt.getReportingUnit());
				contractReceipt.setReportingUnit(unitId);
			}else {
				contractReceipt.setReportingUnitName(unitCount.getApplicantName());
				contractReceipt.setReportingUnit(unitId);
			}
		}
		contractReceiptDao.update(contractReceipt);
	}
	
	@Override
	public void delete(String id){
		contractReceiptDao.delete(id);
	}
	
	@Override
	public void deleteBatch(String[] ids){
		contractReceiptDao.deleteBatch(ids);
	}

	//统计收付款
	@Override
	public ContractReceiptEntity queryPaymenAmount(ContractReceiptEntity contractReceipt) {
		//统计收款总金额
		BigDecimal receiptMoney = contractReceiptDao.receiptMoney(contractReceipt.getProjectId());
		if (receiptMoney != null){
			contractReceipt.setReceiptMoney(receiptMoney);
		}
		//统计付款总金额
		List<String> payList = contractReceiptDao.getPayList(contractReceipt.getProjectId());
		if (payList != null && payList.size() > 0){
			BigDecimal paymentMoney = contractReceiptDao.paymentMoney(payList);
			if (paymentMoney != null){
				contractReceipt.setPaymentMoney(paymentMoney);
			}
		}
		//付款总金额需相加项目法人管理费
		CorporateCheckingEntity corporateCheckingEntity = corporateCheckingService.queryMoney(contractReceipt.getProjectId());
		if (corporateCheckingEntity != null && corporateCheckingEntity.getCorporateCheckingMoney() != null){
			contractReceipt.setPaymentMoney(contractReceipt.getPaymentMoney().add(corporateCheckingEntity.getCorporateCheckingMoney()));
		}
		return contractReceipt;
	}

	@Override
	public List<ContractReceiptExportEntity> getContractReceiptAll(String id) {
		List<ContractReceiptExportEntity> rows = contractReceiptDao.getContractReceiptAll(id);
		if (rows != null && rows.size() > 0){
			for (int i =0 ; i < rows.size() ; i ++){
				rows.get(i).setReceiptMoney(contractReceiptDao.countReceiptMoney(rows.get(i).getId()));
				//计算已收款比例
				if (rows.get(i).getReceiptMoney() != null && rows.get(i).getSettlementMoney() != null){
					//rows.get(i).setReceiptScale(BigDecimalUtils.stringToDate(rows.get(i).getReceiptMoney(),rows.get(i).getSettlementMoney()));
				}
				if (rows.get(i).getId() != null){
					//查询付款合同
					int paymentMoneysInt = 0;
					List<String> paymentIdList = contractReceiptDao.getpaymentIdList(rows.get(i).getId());
					if (paymentIdList != null && paymentIdList.size() > 0){

						for (int k = 0 ; k <paymentIdList.size(); k++){
							//每个合同的付款总额
							BigDecimal paymentMoney = contractReceiptDao.sumPaymentMoney(paymentIdList.get(k));//付款总额
							if (paymentMoney != null){
								paymentMoneysInt = paymentMoneysInt+paymentMoney.intValue();
							}
						}
					}
					//统计收款总金额
					BigDecimal receiptMoney = contractReceiptDao.receiptMoney(id);
					if ((new BigDecimal(paymentMoneysInt)) != null && rows.get(i).getReceiptMoney() != null){
						rows.get(i).setPaymentMoney(new BigDecimal(paymentMoneysInt));
						//计算付款占收款比例
						//rows.get(i).setPaymentScale(BigDecimalUtils.stringToDate(new BigDecimal(paymentMoneysInt),receiptMoney));//付款占收款比例
					}
				}
			}
		}
		return rows;
	}

	@Override
	public Map<String, Object> getContractReceipt(Map<String, Object> params) {
		Map<String,Object> map = new HashedMap();
		params.put("offset",(Integer.parseInt((String)params.get("page"))-1)*Integer.parseInt((String)params.get("rows")));
		params.put("limit",Integer.parseInt((String)params.get("page"))*Integer.parseInt((String)params.get("rows")));
		List<ContractReceiptEntity> rows = contractReceiptDao.getContractReceipt(params);
		if (rows != null && rows.size() > 0){
            for (int i =0 ; i < rows.size() ; i ++){
            	rows.get(i).setReceiptMoney(contractReceiptDao.countReceiptMoney(rows.get(i).getId()));
            	//计算已收款比例
                if (rows.get(i).getReceiptMoney() != null && rows.get(i).getSettlementMoney() != null){
                    rows.get(i).setReceiptScale(BigDecimalUtils.stringToDate(rows.get(i).getReceiptMoney(),rows.get(i).getSettlementMoney()));
                }
                if (rows.get(i).getId() != null){
                    //查询付款合同
                    int paymentMoneysInt = 0;
                    List<String> paymentIdList = contractReceiptDao.getpaymentIdList(rows.get(i).getId());
                    if (paymentIdList != null && paymentIdList.size() > 0){

                        for (int k = 0 ; k <paymentIdList.size(); k++){
                            //每个合同的付款总额
                            BigDecimal paymentMoney = contractReceiptDao.sumPaymentMoney(paymentIdList.get(k));//付款总额
                            if (paymentMoney != null){
                                paymentMoneysInt = paymentMoneysInt+paymentMoney.intValue();
                            }
                        }
                    }
					//统计收款总金额
					BigDecimal receiptMoney = contractReceiptDao.receiptMoney((String) params.get("projectId"));
                    if ((new BigDecimal(paymentMoneysInt)) != null && rows.get(i).getReceiptMoney() != null){
                        rows.get(i).setPaymentMoney(new BigDecimal(paymentMoneysInt));
                        //计算付款占收款比例
						if (receiptMoney.intValue()!=0){
							rows.get(i).setPaymentScale(BigDecimalUtils.stringToDate(new BigDecimal(paymentMoneysInt),receiptMoney));//付款占收款比例
						}else {
							rows.get(i).setPaymentScale("0");
						}
                    }
                }
			}
		}
		map.put("page",(String)params.get("page"));//当前页
		int total = contractReceiptDao.getContractReceiptCount((String)params.get("projectId"));
		map.put("records",total);//总条数
		map.put("total",Math.ceil((Double.valueOf(total))/(Double.valueOf((String) params.get("rows")))));//总页数
		map.put("rows",rows);
		Map<String,Object> userdata = new HashedMap();
		userdata.put("amount",600);
		userdata.put("name","Totals:");
		userdata.put("tax",120);
		userdata.put("total",720);
		map.put("userdata",userdata);
		return map;
	}

    @Override
    public Map<String, Object> getContractPayment(Map<String, Object> params) {
        Map<String,Object> map = new HashedMap();
        params.put("offset",(Integer.parseInt((String)params.get("page"))-1)*Integer.parseInt((String)params.get("rows")));
        params.put("limit",Integer.parseInt((String)params.get("page"))*Integer.parseInt((String)params.get("rows")));
        List<ContractPaymentEntity> rows = contractPaymentDao.getContractPayment(params);
        if (rows != null && rows.size()>0){
            for (int i = 0 ; i < rows.size();i++){
            	if (rows.get(i).getContractTime() != null){
					SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            		rows.get(i).setContractTimeStr(formatter.format(rows.get(i).getContractTime()));
				}
                if (rows.get(i).getPaymentMoney() != null && rows.get(i).getContractTotal() != null){
                	BigDecimal PaymentMoney = rows.get(i).getPaymentMoney();
                	BigDecimal ContractTotal = rows.get(i).getContractTotal();
                    rows.get(i).setPaymentScale(BigDecimalUtils.stringToDate(PaymentMoney,ContractTotal));
                }
            }
        }
        map.put("page",(String)params.get("page"));//当前页
        int total = contractPaymentDao.getContractPaymentCount((String)params.get("contractReceiptId"));
        map.put("records",total);//总条数
        map.put("total",Math.ceil((Double.valueOf(total))/(Double.valueOf((String) params.get("rows")))));//总页数
        map.put("rows",rows);
        return map;
    }

    @Override
    public void deleteContractReceipt(Map<String, Object> map) {
        //先删除收款合同
        contractReceiptDao.deleteContractReceipt((String)map.get("id"));
        //删除付款合同
        List<String> payId = contractReceiptDao.getpaymentIdList((String)map.get("id"));
        if (payId != null && payId.size()>0){
            contractReceiptDao.deleteBatchContractReceiptId(payId);

            contractReceiptDao.deleteBatchContractInfoId(payId);
        }
    }

	@Override
	public void deleteContractPayment(Map<String, Object> map) {

		contractReceiptDao.deleteContractPayment((String)map.get("id"));

		contractReceiptDao.deleteContractPaymentInfo((String)map.get("id"));
	}

	@Override
	public void deletePaymentProportionInfo(Map<String, Object> map) {
		contractReceiptDao.deletePaymentProportionInfo((String)map.get("id"));
	}

	@Override
	public List<ContractReceiptEntity> exportContractOrProportionInfo(Map<String, Object> params) {
		//1.根据项目ID查询收款合同
          List<ContractReceiptEntity> contractReceiptList = contractReceiptDao.getContractReceiptOnLimt((String)params.get("projectId"));//收款合同
          if (contractReceiptList != null && contractReceiptList.size()>0){
          	//2.根据收款合同ID查询付款合同
			  List<String> contractReceiptIdList = new ArrayList<>();
			  for (int i = 0 ; i < contractReceiptList.size(); i++){
			  	contractReceiptIdList.add(contractReceiptList.get(i).getId());
			  }
			  if (contractReceiptIdList != null && contractReceiptIdList.size() > 0){
				  List<ContractPaymentEntity> contractPaymentList = contractReceiptDao.getContractPatment(contractReceiptIdList);//付款合同
				  //3.根据付款合同ID查询支付详情
				  if (contractPaymentList != null && contractPaymentList.size()>0){
				  	//将付款合同加入收款下面
					  for (int h = 0 ; h < contractReceiptList.size(); h++){
						  List<ContractPaymentEntity> ContractPaymentEntityList = new ArrayList<>();
					  	for (int l = 0 ; l < contractPaymentList.size();l++){
							if (contractReceiptList.get(h).getId().equals(contractPaymentList.get(l).getContractReceiptId())){
								ContractPaymentEntityList.add(contractPaymentList.get(l));
							}
						}
                          //查询付款详情条数
						  contractReceiptList.get(h).setSumPaymentInfo(contractReceiptDao.sumPaymentInfo(contractReceiptList.get(h).getId()));
						  contractReceiptList.get(h).setContractPaymentList(ContractPaymentEntityList);
					  }
				  	List<String> contractPaymentIdList = new ArrayList<>();
				  	for(int k = 0 ; k < contractPaymentList.size();k++){
						contractPaymentIdList.add(contractPaymentList.get(k).getId());
					}
					//4.根据付款合同ID查询付款详情
					  if (contractPaymentIdList != null && contractPaymentIdList.size()>0){
					  	List<PaymentInfoEntity> paymentInfoList = contractReceiptDao.getPaymentInfo(contractPaymentIdList);//付款详情
					  	if (paymentInfoList != null && paymentInfoList.size() >0){
                            //将付款详情加入付款合同
							for (int i = 0 ; i < contractPaymentList.size();i++){
								List<PaymentInfoEntity> paymentInfoEntityList = new ArrayList<>();
								for (int k = 0 ; k < paymentInfoList.size();k++){
									if (contractPaymentList.get(i).getId().equals(paymentInfoList.get(k).getContractPaymentId())){
										paymentInfoEntityList.add(paymentInfoList.get(k));
									}
								}
								contractPaymentList.get(i).setPaymentInfoList(paymentInfoEntityList);
							}
						}
					  }
				  }
			  }
           return contractReceiptList;
		  }
		return null;
	}

	@Override
	public void maintainPaymentRatio(ContractReceiptEntity contractReceipt) {
		ContractReceiptEntity contractReceiptEntity = this.queryPaymenAmount(contractReceipt);
		ProjectEntityEntity projectEntityEntity = new ProjectEntityEntity();
		projectEntityEntity.setId(contractReceipt.getProjectId());
		if (contractReceiptEntity.getReceiptMoney() != null && contractReceiptEntity.getPaymentMoney() != null && contractReceiptEntity.getReceiptMoney().intValue()!=0){
			projectEntityEntity.setBigPaymentRatio(BigDecimalUtils.bigDecimal(contractReceiptEntity.getPaymentMoney(),contractReceiptEntity.getReceiptMoney()));
		}else if (contractReceiptEntity.getReceiptMoney() != null && contractReceiptEntity.getPaymentMoney() == null&& contractReceiptEntity.getReceiptMoney().intValue()!=0){
			projectEntityEntity.setBigPaymentRatio(BigDecimalUtils.bigDecimal(new BigDecimal(0),contractReceiptEntity.getReceiptMoney()));
		}else if (contractReceiptEntity.getReceiptMoney() == null && contractReceiptEntity.getPaymentMoney() != null){
			projectEntityEntity.setBigPaymentRatio(new BigDecimal(0));
		}else {
			projectEntityEntity.setBigPaymentRatio(new BigDecimal(0));
		}
		if (StringUtils.isNotBlank(projectEntityEntity.getId()) && projectEntityEntity.getBigPaymentRatio() != null){
			projectEntityDao.update(projectEntityEntity);
		}
	}

	@Override
	public BigDecimal sumContractTotal(String tenderBatch) {
		return contractReceiptDao.sumContractTotal(tenderBatch);
	}

}
